`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2020/10/20 10:38:43
// Design Name: 
// Module Name: trigger_out
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////

//! 经过 ILA 测试，本模块无问题
module trigger_out(
    input           clk,
    input           rst_n,
    input           key,
    
    output  reg     trigger
    );
localparam  trig_time   = 32'd2;//us
localparam  door_time   = 32'd2000000;//us

//state
localparam  IDLE    = 2'd0;
localparam  TRIG    = 2'd1;
localparam  WAIT    = 2'd2;

reg [1:0]   state;
reg [31:0]  trig_cnt;
reg [31:0]  wait_cnt;

always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        trigger <= 0;
    end else begin
        case (state)
            IDLE: begin
                trigger     <= 0;
                trig_cnt    <= 0;
                wait_cnt    <= 0;
                if (key == 0) begin
                    state   <= TRIG;
                    trigger <= 1;
                end
            end
            TRIG: begin
                trigger <= 1;
                if (trig_cnt >= trig_time - 1) begin
                    state       <= WAIT;
                    trig_cnt    <= 0;
                end else begin
                    trig_cnt    <= trig_cnt + 1;
                end
            end
            WAIT: begin
                trigger <= 0;
                if (wait_cnt >= door_time - 1) begin
                    state       <= IDLE;
                    wait_cnt    <= 0;
                end else begin
                    wait_cnt    <= wait_cnt + 1;
                end
            end
            default: begin
                state <= IDLE;
            end
        endcase
    end
end

endmodule
